﻿using IdentityServer4.Models;
using IdentityServer4.Validation;
using System.Security.Claims;


namespace Demo.Net.IdentityServer.IdentityServer.Validator
{
    /// <summary>
    /// 帐号密码登录
    /// </summary>
    public class WxLoginGrantValidator : IExtensionGrantValidator
    {
        /// <summary>
        /// 自定义用户授权类型
        /// </summary>
        public string GrantType
        {
            get
            {
                return GrantTypeConst.WxLoginGrant;
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="microService"></param>
        public WxLoginGrantValidator(IServiceProvider serviceProvider)
        {
        }

        /// <summary>
        /// 授权认证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            try
            {
                await Task.Yield();

                //var user_name = context.Request.Raw["user_name"];  // 帐号
                //var user_pwd = context.Request.Raw["user_pwd"];  // 密码

                //if (string.IsNullOrWhiteSpace(user_name))
                //{
                //    context.Result = new GrantValidationResult
                //    (
                //        error: TokenRequestErrors.InvalidGrant,
                //        errorDescription: "帐号不能为空"
                //    );

                //    return;
                //}
                //if (string.IsNullOrWhiteSpace(user_pwd))
                //{
                //    context.Result = new GrantValidationResult
                //    (
                //        error: TokenRequestErrors.InvalidGrant,
                //        errorDescription: "密码不能为空"
                //    );

                //    return;
                //}

                // 获取用户基本信息
                context.Result = new GrantValidationResult
                (
                    subject: "demonet_wx",
                    authenticationMethod: GrantType,
                    claims: new List<Claim>
                    {
                        new Claim("name","demonet_wx"),
                        new Claim(ClaimTypes.NameIdentifier,"2")
                    }
                );
            }
            catch (Exception ex)
            {
                context.Result = new GrantValidationResult
                (
                    error: TokenRequestErrors.InvalidGrant,
                    errorDescription: ex.Message
                );
            }
        }
    }
}
